package com.shxc.smarttrade.old.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.old.activity.ChangeStopLossOrProfitActivity;
import com.shxc.smarttrade.old.activity.StockChartUpgradeActivity;
import com.shxc.smarttrade.old.bean.ClosePosition;
import com.shxc.smarttrade.old.bean.EventDatas;
import com.shxc.smarttrade.old.bean.RealTimeQuoteDatas;
import com.shxc.smarttrade.old.bean.TraderOrder;
import com.shxc.smarttrade.old.constants.EventContents;
import com.shxc.smarttrade.old.constants.URLContents;
import com.shxc.smarttrade.old.myview.CommonDialog;
import com.shxc.smarttrade.old.utils.Arith;
import com.shxc.smarttrade.old.utils.BaseUtils;
import com.shxc.smarttrade.old.utils.CountClass;
import com.shxc.smarttrade.old.utils.MyOkHttpUtils;
import com.shxc.smarttrade.old.utils.SpUtils;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.shxc.smarttrade.R.id.tv_close_price;

/**
 * Created by jcdev1 on 2017/5/25.
 */

public class ClosePositionFragment extends Fragment {

    @BindView(R.id.tv_all_profit_loss)
    TextView tvAllProfitLoss;
    @BindView(R.id.tv_profit_loss)
    TextView tvProfitLoss;
    @BindView(R.id.tv_storage_free)
    TextView tvStorgeFree;
    @BindView(R.id.tv_handling_charge)
    TextView tvHandLingCharge;

    @BindView(R.id.tv_ticket)
    TextView tvTicket;
    @BindView(R.id.tv_cmd)
    TextView tvCmd;
    @BindView(R.id.tv_openprice)
    TextView tvOpenprice;
    @BindView(R.id.tv_real_time_price)
    TextView tvRealTimePrice;
    @BindView(R.id.tv_hands)
    TextView tvHands;
    @BindView(R.id.tv_margin)
    TextView tvMargin;
    @BindView(R.id.tv_stop_loss_price)
    TextView tvStopLossPrice;
    @BindView(R.id.tv_stop_profit_price)
    TextView tvstopProfitPrice;
    @BindView(R.id.tv_open_time)
    TextView tvOpenTime;
    @BindView(R.id.ll_info)
    LinearLayout llInfo;
    @BindView(R.id.iv_arrow)
    ImageView ivArrow;
    @BindView(R.id.tv_follow_status)
    TextView tvFollowSTatus;
    private Runnable runnable;


    private View rootView;
    private double noPendingTimes;//购买手数（待提交参数volume）
    public int selectWhatNoPended = 0;//未开启挂单选择买涨还是买跌 0：买涨 1：买跌
    private double ask;//实时买价
    private double bid;//实时卖价
    private boolean profitChange = false;//盈亏是否要转化成美元
    private boolean profitUSDPrex = false;//盈亏是否已美元为基础货币
    private int contracSize;//合约数
    private PopupWindow popupWindow;
    private TraderOrder traderOrder;
    private String ticket;//订单号
    private int isRefresh = 0;//返回到持仓界面后是否需要刷新
    private int digits = -1;//小数点后位数
    private boolean quickClosePosition = false;
    private int showTime = 5000;
    private boolean isFinishActivity = false;//是否在popupWindow消失时关闭Activity


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ClosePosition cp = (ClosePosition) msg.obj;
            showTime = 5000;
            isRefresh = 1;

            View view = View.inflate(getContext(), R.layout.pop_close_position, null);
            TextView tvChName = (TextView) view.findViewById(R.id.tv_ch_name);
            TextView tvEnName = (TextView) view.findViewById(R.id.tv_en_name);
            ImageView tvTradeStatus = (ImageView) view.findViewById(R.id.tv_trade_status);
            TextView tvValume = (TextView) view.findViewById(R.id.tv_valume);
            TextView tvProfit = (TextView) view.findViewById(R.id.tv_profit);
            TextView tvClosePrice = (TextView) view.findViewById(tv_close_price);
            tvChName.setText(cp.getSymbolCn());
            tvEnName.setText(cp.getSymbolEn());
            tvValume.setText(cp.getVolume() + "手");
            if (cp.getProfit() > 0)
                tvProfit.setTextColor(getResources().getColor(R.color.tab_text));
            else
                tvProfit.setTextColor(getResources().getColor(R.color.stock_fell_color));
            tvProfit.setText(BaseUtils.dealSymbol(cp.getProfit()));
            tvClosePrice.setText(BaseUtils.getDigitsData(cp.getClosePrice(), digits));

            if (cp.getCmd() == 0) {
                tvTradeStatus.setImageResource(R.mipmap.icon_buy);
            } else {
                tvTradeStatus.setImageResource(R.mipmap.icon_sell);
            }
            isFinishActivity = true;
            showPopupWindow(view);
            runnable = new Runnable() {
                @Override
                public void run() {
                    showTime -= 1000;
                    if (showTime == 0) {
                        handler.removeCallbacks(runnable);
                        popupWindow.dismiss();
                        getActivity().finish();

                    } else
                        handler.postDelayed(runnable, 1000);
                }
            };
            handler.post(runnable);

        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_close_position, null);
        }
        //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        EventBus.getDefault().register(this);
        ButterKnife.bind(this, rootView);
        initView();
        return rootView;
    }

    /**
     * 初始化View
     */
    private void initView() {
        Intent intent = getActivity().getIntent();
        traderOrder = (TraderOrder) intent.getSerializableExtra("traderOrder");
        quickClosePosition = SpUtils.getBoolean(getActivity(), "quickClosePosition", false);

        digits = traderOrder.getDigits();
        if (traderOrder.getProfit() > 0)
            tvProfitLoss.setTextColor(getResources().getColor(R.color.stock_rise_color));
        else
            tvProfitLoss.setTextColor(getResources().getColor(R.color.stock_fell_color));
        double allPL = Arith.add(Arith.add(traderOrder.getProfit(), traderOrder.getSwaps()), traderOrder.getCommission());
        if (allPL > 0)
            tvAllProfitLoss.setTextColor(getResources().getColor(R.color.stock_rise_color));
        else
            tvAllProfitLoss.setTextColor(getResources().getColor(R.color.stock_fell_color));
        tvAllProfitLoss.setText(BaseUtils.dealSymbol(allPL));
        tvProfitLoss.setText(BaseUtils.dealSymbol(traderOrder.getProfit()));
        tvStorgeFree.setText(BaseUtils.dealSymbol(traderOrder.getSwaps()));
        tvHandLingCharge.setText(BaseUtils.dealSymbol(traderOrder.getCommission()));
//        Log.e("tp::", traderOrder.getTp() + "");
        ticket = traderOrder.getTicket();
        tvTicket.setText(traderOrder.getTicket() + "");
        if (traderOrder.getCmd() == 0) {
            tvCmd.setText("买涨");
            tvRealTimePrice.setText(BaseUtils.getDigitsData(traderOrder.getBid(), digits));
        } else {
            tvCmd.setText("买跌");
            tvRealTimePrice.setText(BaseUtils.getDigitsData(traderOrder.getAsk(), digits));
        }

        tvOpenprice.setText(BaseUtils.getDigitsData(traderOrder.getOpenPrice(), digits));
        tvHands.setText(traderOrder.getVolume() + "");
        tvMargin.setText("$" + BaseUtils.getDigitsData(traderOrder.getMargin(), 2));
        if (traderOrder.getSl() == 0) tvStopLossPrice.setText("未设置");
        else tvStopLossPrice.setText(BaseUtils.getDigitsData(traderOrder.getSl(), digits));
        if (traderOrder.getTp() == 0) tvstopProfitPrice.setText("未设置");
        else tvstopProfitPrice.setText(BaseUtils.getDigitsData(traderOrder.getTp(), digits));
        tvOpenTime.setText(traderOrder.getOpenTime() + "");
        if (traderOrder.getIsCopy() == 1)
            tvFollowSTatus.setText("跟随中");
        else
            tvFollowSTatus.setText("未跟随");
    }

    /**
     * 实时数据，由Activity提供
     */
    public void setRealTimeDatas(List<RealTimeQuoteDatas.DataBean.QuoteBean> quoteBeen) {

        if (getActivity()==null) {
            return;
        }

        if (quoteBeen != null && quoteBeen.size() > 0) {
            //用于展示页面上的的基本数据
            if (tvProfitLoss == null) return;

            ask = quoteBeen.get(0).getAsk();
            bid = quoteBeen.get(0).getBid();
            double[] askBidOne = new double[]{ask, bid};
            double[] askBidTwo = null;
            if (quoteBeen.size() > 1)
                askBidTwo = new double[]{quoteBeen.get(1).getAsk(), quoteBeen.get(1).getBid()};
            double market = quoteBeen.get(0).getMarket();
            double profit = CountClass.getProfit(askBidOne, traderOrder.getOpenPrice(), traderOrder.getCmd(), askBidTwo, traderOrder.getContractSize(), traderOrder.getVolume(), traderOrder.isProfitChange(), traderOrder.isProfitUSDPrex());
            if (profit > 0) {
                tvProfitLoss.setTextColor(getResources().getColor(R.color.stock_rise_color));
            } else {
                tvProfitLoss.setTextColor(getResources().getColor(R.color.stock_fell_color));
            }

            tvProfitLoss.setText(BaseUtils.dealSymbol(profit));
            double allPL = Arith.add(Arith.add(profit, traderOrder.getSwaps()), traderOrder.getCommission());
            if (allPL > 0)
                tvAllProfitLoss.setTextColor(getResources().getColor(R.color.stock_rise_color));
            else
                tvAllProfitLoss.setTextColor(getResources().getColor(R.color.stock_fell_color));
            tvAllProfitLoss.setText(BaseUtils.dealSymbol(allPL));
            if (traderOrder.getCmd() == 0)
                tvRealTimePrice.setText(BaseUtils.getDigitsData(bid, digits));
            else
                tvRealTimePrice.setText(BaseUtils.getDigitsData(ask, digits));
        }
    }

    /**
     * 必须加注解，否则无效
     * 接收Activity界面按钮点击对象
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventDatas event) {
        if (event.getTagOne().equals(EventContents.STOCK_CHART_UPGRADE_ACTIVITY_FIVE)) {
            //调整止盈止损
            Intent intent = new Intent(getActivity(), ChangeStopLossOrProfitActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("traderOrder", traderOrder);
            intent.putExtras(bundle);
            startActivity(intent);
            MobclickAgent.onEvent(getContext(), "change_loss_profit");//友盟统计该点击事件发生次数

        } else if (event.getTagOne().equals(EventContents.STOCK_CHART_UPGRADE_ACTIVITY_SIX)) {
            //close
            if (quickClosePosition)
                closePosition(ticket, SpUtils.getInt(getActivity().getApplicationContext(), "userId"));
            else
                showClosePositionDialog(ticket);
        } else if (event.getTagOne().equals(EventContents.CHANGE_STOPLOSS_OR_PROFIT)) {
            double[] dou = (double[]) event.getResponse();
            if (dou[0] != 0) {
                tvstopProfitPrice.setText(BaseUtils.getDigitsData(dou[0], digits));
                traderOrder.setTp(dou[0]);
                isRefresh = 1;
            }
            if (dou[1] != 0) {
                tvStopLossPrice.setText(BaseUtils.getDigitsData(dou[1], digits));
                traderOrder.setSl(dou[1]);
                isRefresh = 1;
            }
        }

    }

    /**
     * 弹出平仓提示框
     */
    private void showClosePositionDialog(final String ticket) {
        CommonDialog commonDialog = new CommonDialog(getActivity(), R.style.customDialogStyle);
        commonDialog.setCanceledOnTouchOutside(true);
        commonDialog.setBaseText("提示", "是否确认平仓", "取消", "确定");
        commonDialog.setYesCLickRunAble(new Runnable() {
            @Override
            public void run() {
                ((StockChartUpgradeActivity) getActivity()).showDialog();
                closePosition(ticket, SpUtils.getInt(getActivity().getApplicationContext(), "userId"));
                MobclickAgent.onEvent(getContext(), "close_position");//友盟统计该点击事件发生次数
            }
        });
        commonDialog.show();
    }


    /**
     * close
     *
     * @param ticket
     * @param userId
     */
    private void closePosition(String ticket, int userId) {
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", SpUtils.getString(getContext(), "accessToken", ""));
        map.put("ticket", ticket + "");
        map.put("userId", userId + "");
        MyOkHttpUtils.getServiceDatas(getActivity(),map, URLContents.CLOSE_POSITION_FRAGMENT_CLOSE, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                ((StockChartUpgradeActivity) getActivity()).showToast("网络异常");
                ((StockChartUpgradeActivity) getActivity()).dismissDialog();
            }

            @Override
            public void success(String response, int id) {
//                Log.e("close", response);
                if (response != null) {
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = "";
                    String errMsg = "";
                    if (!jsonObject.get("err_code").isJsonNull())
                        errCode = jsonObject.get("err_code").getAsString();
                    if (!jsonObject.get("err_msg").isJsonNull())
                        errMsg = jsonObject.get("err_msg").getAsString();
                    if (errCode.equals("0")) {
                        if (!jsonObject.get("data").isJsonNull()) {
                            JsonObject data = jsonObject.get("data").getAsJsonObject();
                            if (!data.get("closeTrader").isJsonNull()) {
                                JsonObject closeTrader = data.get("closeTrader").getAsJsonObject();
                                Gson gson = new Gson();
                                ClosePosition cp = gson.fromJson(closeTrader, ClosePosition.class);

                                Message msg = Message.obtain();
                                msg.obj = cp;
                                handler.sendMessage(msg);
                            }
                        }

                    } else {
                        if (getActivity() != null)
                            ((StockChartUpgradeActivity) getActivity()).showToast(errMsg);
                    }

                }
                ((StockChartUpgradeActivity) getActivity()).dismissDialog();
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().post(new EventDatas(EventContents.CLOSE_POSITION_FRAGMENT_ONE, new int[]{((StockChartUpgradeActivity) getActivity()).tagFrom, isRefresh}));
        EventBus.getDefault().unregister(this);
    }


    /**
     * 显示操作对话框
     *
     * @param mainView
     */
    public void showPopupWindow(View mainView) {
        popupWindow = new PopupWindow(mainView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setAnimationStyle(R.style.AnimationBottonAndTop);
        popupWindow.showAtLocation(View.inflate(getContext(), R.layout.activity_stock_chart, null), Gravity.BOTTOM, 0, 0);
        setBackgroundAlpha(0.7f);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBackgroundAlpha(1f);
                if (runnable != null && handler != null) {
                    handler.removeCallbacks(runnable);
                }
                if (isFinishActivity)
                    getActivity().finish();
            }
        });


    }

    /**
     * 设置popupwindow背景色
     *
     * @param bgAlpha
     */
    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getActivity().getWindow().setAttributes(lp);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    private boolean isShowInfo = false;

    @OnClick({R.id.ll_all})
    public void onViewClicked(View view) {
        if (isShowInfo) {
            llInfo.setVisibility(View.GONE);
            ivArrow.setImageResource(R.mipmap.arrow_down);
            isShowInfo = false;
        } else {
            llInfo.setVisibility(View.VISIBLE);
            ivArrow.setImageResource(R.mipmap.arrow_up);

            isShowInfo = true;

        }
    }
}
